﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BluePig.WebApi.Models;

namespace BluePig.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TracesController : ControllerBase
    {
        private readonly BluePigContext _context;

        public TracesController(BluePigContext context)
        {
            _context = context;
        }

        // GET: api/Traces
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Trace>>> GetTraces()
        {
            return await _context.Traces.ToListAsync();
        }

        // GET: api/Traces/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Trace>> GetTrace(int id)
        {
            var trace = await _context.Traces.FindAsync(id);

            if (trace == null)
            {
                return NotFound();
            }

            return trace;
        }

        // PUT: api/Traces/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTrace(int id, Trace trace)
        {
            if (id != trace.Id)
            {
                return BadRequest();
            }

            _context.Entry(trace).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TraceExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Traces
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Trace>> PostTrace(Trace trace)
        {
            _context.Traces.Add(trace);
            await _context.SaveChangesAsync();

             CreatedAtAction("GetTrace", new { id = trace.Id }, trace);
            return Ok();
        }

        // DELETE: api/Traces/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteTrace(int id)
        {
            var trace = await _context.Traces.FindAsync(id);
            if (trace == null)
            {
                return NotFound();
            }

            _context.Traces.Remove(trace);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool TraceExists(int id)
        {
            return _context.Traces.Any(e => e.Id == id);
        }
    }
}
